package com.example.test2.db.control;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.test2.db.gen.BuyDao;
import com.example.test2.db.gen.DaoMaster;
import com.example.test2.db.gen.DaoSession;
import com.example.test2.db.entity.Buy;

import java.util.List;

// TODO: 2024/5/29 采购数据库管理类
public class BuyDbController {
    /**
     * Helper
     */
    private DaoMaster.DevOpenHelper mHelper;//获取Helper对象
    /**
     * 数据库
     */
    private SQLiteDatabase db;
    /**
     * DaoMaster
     */
    private DaoMaster mDaoMaster;
    /**
     * DaoSession
     */
    private DaoSession mDaoSession;
    /**
     * 上下文
     */
    private Context context;
    /**
     * dao
     */
    private BuyDao buyDao;

    private static BuyDbController mDbController;

    /**
     * 获取单例
     */
    public static BuyDbController getInstance(Context context){
        if(mDbController == null){
            synchronized (BuyDbController.class){
                if(mDbController == null){
                    mDbController = new BuyDbController(context);
                }
            }
        }
        return mDbController;
    }
    /**
     * 初始化
     * @param context
     */
    public BuyDbController(Context context) {
        this.context = context;
        mHelper = new DaoMaster.DevOpenHelper(context,"buy.db", null);
        mDaoMaster =new DaoMaster(getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
        buyDao = mDaoSession.getBuyDao();
    }
    /**
     * 获取可读数据库
     */
    private SQLiteDatabase getReadableDatabase(){
        if(mHelper == null){
            mHelper = new DaoMaster.DevOpenHelper(context,"buy.db",null);
        }
        SQLiteDatabase db =mHelper.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     * @return
     */
    private SQLiteDatabase getWritableDatabase(){
        if(mHelper == null){
            mHelper =new DaoMaster.DevOpenHelper(context,"buy.db",null);
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        return db;
    }

    /**
     * 会自动判定是插入还是替换
     * @param video
     */
    public void insertOrReplace(Buy video){
        buyDao.insertOrReplace(video);
    }

    /**
     * 按条件查询数据
     */
    public List<Buy> searchByName(String name){
        List<Buy> video = buyDao.queryBuilder().where(BuyDao.Properties.Name.eq(name)).list();
        return video;
    }

    /**
     * 查询所有数据
     */
    public List<Buy> searchAll(){
        List<Buy>videos=buyDao.queryBuilder().list();
        return videos;
    }

}